<!-- eslint-disable vue/multi-word-component-names -->
<!-- @Author: NWJ
        Version: 1.0 -->

<template>
  <div class="message-management">
    <el-card>
      <el-form :inline="true" :model="filterForm" class="demo-form-inline">
        <el-form-item label="消息标题">
          <el-input v-model="filterForm.title" placeholder="请输入消息标题"></el-input>
        </el-form-item>
        <el-form-item label="发送人ID">
          <el-input v-model="filterForm.sendId" placeholder="请输入发送人ID"></el-input>
        </el-form-item>
        <el-form-item label="接收人ID">
          <el-input v-model="filterForm.acceptId" placeholder="请输入接收人ID"></el-input>
        </el-form-item>
        <el-form-item label="是否已读">
          <el-select v-model="filterForm.isRead" placeholder="请选择">
            <el-option label="全部" value=""></el-option>
            <el-option label="已读" value="yes"></el-option>
            <el-option label="未读" value="no"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否系统消息">
          <el-select v-model="filterForm.isSystem" placeholder="请选择">
            <el-option label="全部" value=""></el-option>
            <el-option label="是" value="yes"></el-option>
            <el-option label="否" value="no"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onFilter">查询</el-button>
        </el-form-item>
      </el-form>

      <el-table
        :data="filteredMessages"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="80"></el-table-column>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="title" label="消息标题" width="180"></el-table-column>
        <el-table-column prop="sendId" label="发送人ID" width="120"></el-table-column>
        <el-table-column prop="acceptId" label="接收人ID" width="120"></el-table-column>
        <el-table-column prop="isRead" label="是否已读" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.isRead === 'yes' ? 'success' : 'info'">
              {{ scope.row.isRead === 'yes' ? '已读' : '未读' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isSystem" label="是否系统消息" width="160">
          <template #default="scope">
            <el-tag :type="scope.row.isSystem === 'yes' ? 'success' : 'info'">
              {{ scope.row.isSystem === 'yes' ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="200">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <el-dialog v-model="dialogVisible" title="消息详情" width="30%">
      <el-form :model="currentMessage" label-width="100px">
        <el-form-item label="消息标题">
          <el-input v-model="currentMessage.title"></el-input>
        </el-form-item>
        <el-form-item label="消息正文">
          <el-input type="textarea" v-model="currentMessage.content"></el-input>
        </el-form-item>
        <el-form-item label="发送人ID">
          <el-input v-model="currentMessage.sendId" disabled></el-input>
        </el-form-item>
        <el-form-item label="接收人ID">
          <el-input v-model="currentMessage.acceptId" disabled></el-input>
        </el-form-item>
        <el-form-item label="是否已读">
          <el-select v-model="currentMessage.isRead" disabled>
            <el-option label="已读" value="yes"></el-option>
            <el-option label="未读" value="no"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否系统消息">
          <el-select v-model="currentMessage.isSystem" disabled>
            <el-option label="是" value="yes"></el-option>
            <el-option label="否" value="no"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="currentMessage.createdAt"
            type="datetime"
            placeholder="选择日期时间"
            disabled
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { showMsg } from '@/utils/showMsg'

export default {
  data()
  {
    return {
      messages: [], // 所有消息数据
      filteredMessages: [], // 过滤后的消息数据
      filterForm: {
        title: '',
        sendId: '',
        acceptId: '',
        isRead: '',
        isSystem: ''
      },
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      currentMessage: {},
      selectedMessages: []
    }
  },
  created()
  {
    this.fetchMessages()
  },
  methods: {
    // 从后端获取所有消息（带分页）
    async fetchMessages()
    {
      if (!this.$store.getters.isLoggedIn)
      {
        showMsg('登录状态失效', '请重新登录', 'warning')
        this.$router.push('/login')
        return
      }

      try
      {
        const response = await axios.get(`/node/msgs/getAll?page=${this.currentPage}&size=${this.pageSize}`, {
          params: this.filterForm
        })
        this.messages = response.data.data.data || []
        this.filteredMessages = [...this.messages] // 初始过滤后数据
        this.total = response.data.total || 0 // 假设后端返回 total 字段表示总条数
      }
      catch (error)
      {
        showMsg('数据加载失败', '无法获取消息列表，请检查网络或联系管理员', 'error')
        console.error('Error fetching messages:', error)
      }
    },

    // 过滤消息
    onFilter()
    {
      this.currentPage = 1 // 重置到第一页
      this.fetchMessages()
    },

    // 更新分页数据
    updatePagination()
    {
      // 由于后端已处理分页，这里仅更新当前页数据
      this.fetchMessages()
    },

    // 每页显示条数变化
    handleSizeChange(size)
    {
      this.pageSize = size
      this.updatePagination()
    },

    // 当前页变化
    handleCurrentChange(page)
    {
      this.currentPage = page
      this.updatePagination()
    },

    // 选择行变化
    handleSelectionChange(selection)
    {
      this.selectedMessages = selection
    },

    // 查看消息详情
    handleView(message)
    {
      this.currentMessage = { ...message, createdAt: new Date(message.createdAt) }
      this.dialogVisible = true
    },

    // 保存消息（通过后端更新）
    async handleSave()
    {
      if (!this.$store.getters.isLoggedIn)
      {
        showMsg('登录状态失效', '请重新登录', 'warning')
        this.$router.push('/login')
        return
      }

      try
      {
        const payload = {
          title: this.currentMessage.title,
          content: this.currentMessage.content,
          // sendId 和 acceptId 不允许修改，保持原值
          sendId: this.currentMessage.sendId,
          acceptId: this.currentMessage.acceptId,
          isRead: this.currentMessage.isRead,
          isSystem: this.currentMessage.isSystem
        }

        await axios.put(`/node/msgs/${this.currentMessage.id}`, payload)
        showMsg('保存成功', '消息已更新', 'success')
        this.dialogVisible = false
        this.fetchMessages() // 刷新消息列表
      }
      catch (error)
      {
        showMsg('保存失败', '消息更新失败，请重试', 'error')
      }
    },

    // 删除消息
    handleDelete(message)
    {
      this.$confirm('确定要删除该消息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() =>
      {
        try
        {
          await axios.delete(`/node/msgs/${message.id}`) // 假设后端提供删除接口
          this.messages = this.messages.filter(msg => msg.id !== message.id)
          this.onFilter()
          showMsg('删除成功', '消息已删除', 'success')
        }
        catch (error)
        {
          showMsg('删除失败', '消息删除失败，请重试', 'error')
        }
      }).catch(() =>
      {
        showMsg('已取消删除', '取消了删除操作', 'info')
      })
    },

    // 格式化时间
    formatDate(dateString)
    {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }).replace(/\//g, '-')
    }
  }
}
</script>

<style scoped>
* { font-size: 12px; }
.message-management {
  height: 90vh;
  position: relative;
  z-index: 1;
  padding: 20px;
}

.el-table .cell {
  font-size: 12px; /* 确保表格内容字体大小一致 */
}
</style>
